// 导入路由模块下的静态路由表
import { constantRoutes, asyncRoutes } from '@/router/index'

const state = () => {
  return {
    // 路由表:初始值是静态路由表的值
    routes: constantRoutes
  }
}

const mutations = {
  // 设置
  setRoutes: (state, showAsyncRoutes) => {
    // state.routes.push(...showAsyncRoutes)
    // 给routes数组追加筛选后的动态路由表
    state.routes = [
      ...constantRoutes,
      ...showAsyncRoutes
    ]
  },
  // 清空
  removeRoutes: () => {
    state.routes = []
  }
}

const actions = {
  // 筛选动态路由表
  filterAsync: ({ commit }, menus) => {
    // 基于动态路由表和menus数组筛选，
    const showRouter = asyncRoutes
      .filter(item => menus.includes(item.children[0].name))
    // 提交mutation
    commit('setRoutes', showRouter)
    // 返回筛选结果给路由守卫用
    return showRouter
  }
}

export default {
  namespaced: true, // 开启命名空间防止重名
  state,
  mutations,
  actions
}
